#include "CBrowse.h"

bool CBrowse::getAllFiles(Document &send,char *path)
{
	try
	{
		
		Pointer("/result/0").Create(send);
		Value* result = GetValueByPointer(send,"/result");

		DIR *d;
		struct dirent *dir;
		d = opendir(path);
		if(d)
		{
			while((dir = readdir(d)) != NULL)
			{	
				char abspath[300];
				if(path[strlen(path)-1]=='/')
					sprintf(abspath,"%s%s",path,dir->d_name);
				else 
					sprintf(abspath,"%s/%s",path,dir->d_name);
				if(isFile(abspath)==1)
				{
					Value val(dir->d_name, send.GetAllocator());												
					result->PushBack(val,send.GetAllocator());
	
				}
			}
		}
		if(GetValueByPointer(send,"/result/0")->IsNull())
			EraseValueByPointer(send,"/result/0");
	}
	catch(...)
	{
		return false;
	}
	return true;
}
bool CBrowse::getJsonFiles(Document &send,char *path)
{
	try
	{
		Pointer("/result/0").Create(send);
		Value* result = GetValueByPointer(send,"/result");

		DIR *d;
		struct dirent *dir;
		d = opendir(path);
		if(d)
		{
			while((dir = readdir(d)) != NULL)
			{
				char abspath[300];
				if(path[strlen(path)-1]=='/')
					sprintf(abspath,"%s%s",path,dir->d_name);
				else 
					sprintf(abspath,"%s/%s",path,dir->d_name);
				if(isFile(abspath)>0&&isJson(abspath)>0)
				{
					Value val(dir->d_name, send.GetAllocator());
					result->PushBack(val,send.GetAllocator());
				}
			}
		}
		if(GetValueByPointer(send,"/result/0")->IsNull())
			EraseValueByPointer(send,"/result/0");

	}
	catch(...)
	{
		return false;
	}
	return true;

}
bool CBrowse::isFile(char *path)
{
	DIR *directory = opendir(path);
	if(directory != NULL)
	{
		closedir(directory);
		return 0;
	}
	if(errno == ENOTDIR)
	{
		return 1;
	}
	return -1;
}
bool CBrowse::isJson(char *path)
{
	try
	{
		int len = strlen(path);
		int pos = len;
		for(int i=len-1;i>=0;i--)
			if(path[i]=='.')
				pos = i;
		if(strcmp(path+pos,".json")==0) return 1;
		else return 0;

	}
	catch(...)
	{
		return -1;
	}
}
